<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('inOutStock.inStockOrder.no')" clearable prop="no">
        <el-input
          v-model="queryParams.no"
          :placeholder="$t('enterTip') + $t('inOutStock.inStockOrder.no')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('status')" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" clearable :placeholder="$t('selectTip') + $t('status')"  >
          <el-option
            v-for="dict in dict.type.invoice_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('inOutStock.inStockOrder.relOrderNo')" clearable prop="relOrderNo">
        <el-input
          v-model="queryParams.relOrderNo"
          :placeholder="$t('enterTip') + $t('inOutStock.inStockOrder.relOrderNo')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('search')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('reset')}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="btnGroup">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          v-if="pageInit.orderType === '8'"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inOutStock:inStockOrder:add']"
        >{{$t('add')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          v-if="pageInit.orderType === '8'"
          icon="el-icon-edit"
          size="mini"
          :disabled="single || !selectRow[0] || selectRow[0].orderStatus !== 1"
          @click="handleUpdate"
          v-hasPermi="['inOutStock:inStockOrder:edit']"
        >{{$t('edit')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          v-if="!['5','6','8'].includes(pageInit.orderType)"
          icon="el-icon-close"
          size="mini"
          :disabled="single || !selectRow[0] || selectRow[0].orderStatus !== 1"
          @click="handleCancel"
          v-hasPermi="['inOutStock:inStockOrder:cancel']"
        >{{$t('cancel')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          v-if="pageInit.orderType === '8'"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inOutStock:inStockOrder:remove']"
        >{{$t('delete')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inOutStock:inStockOrder:export']"
        >{{$t('export')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" :height="calcTableHeight"
              highlight-current-row @current-change="rowSelection">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column :label="$t('inOutStock.inStockOrder.no')" align="center" prop="no" width="120" />
      <el-table-column :label="$t('status')" align="center" prop="orderStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.invoice_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('inOutStock.inStockOrder.relOrderNo')" v-if="pageInit.orderType !== '8'" align="center" prop="relOrderNo" width="120"/>
      <el-table-column :label="$t('inOutStock.inStockOrder.area')" v-if="['1','2','3'].includes(pageInit.orderType)" align="center" prop="area" width="120"/>
      <el-table-column :label="$t('inOutStock.inStockOrder.lineSideWarehouseNo')" v-if="['1','2','3'].includes(pageInit.orderType)" align="center" prop="lineSideWarehouseNo" width="120"/>
      <el-table-column :label="$t('inOutStock.inStockOrder.lineSideWarehouseName')" v-if="['1','2','3'].includes(pageInit.orderType)" align="center" prop="lineSideWarehouseName" width="120"/>
      <el-table-column :label="$t('inOutStock.inStockOrder.customerName')" v-if="['4','9'].includes(pageInit.orderType)" align="center" prop="customerName" width="100" />
      <el-table-column :label="$t('inOutStock.inStockOrder.site')" v-if="pageInit.orderType === '7'" align="center" prop="site" width="120" />
      <el-table-column :label="$t('inOutStock.inStockOrder.cause')" v-if="pageInit.orderType === '8'" align="center" prop="cause" width="160" />

      <el-table-column :label="$t('inOutStock.inStockOrder.completeTime')" align="center" prop="completeTime" width="180"/>

      <el-table-column :label="$t('inOutStock.inStockOrder.totalQty')" v-if="['1','2','3','4','9'].includes(pageInit.orderType)" align="center" prop="totalQty" />
      <el-table-column :label="$t('inOutStock.inStockOrder.totalActualQty')" v-if="['1','2','3','4','9'].includes(pageInit.orderType)" align="center" prop="totalActualQty" />
      <el-table-column :label="$t('remark')" v-if="pageInit.orderType === '8'"  align="center" prop="remark" width="160" />

      <el-table-column :label="$t('createUser')" align="center" prop="createByName" min-width="100"/>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="152"/>
      <el-table-column :label="$t('updateUser')" align="center" prop="updateByName" min-width="100"/>
      <el-table-column :label="$t('updateTime')" align="center" prop="updateTime" width="152"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--   单据明细 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
      <el-tab-pane :label="$t('inOutStock.inStockOrder.orderDetail')" name="detailList">
        <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('inOutStock.inStockOrder.cause')" prop="cause">
          <el-input v-model="form.cause" :placeholder="$t('inputTip') + $t('inOutStock.inStockOrder.cause')" />
        </el-form-item>
        <el-form-item :label="$t('remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('inputTip') + $t('remark')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('sure')}}</el-button>
        <el-button @click="cancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>

    <!-- 取消对话框 -->
    <el-dialog :title="$t('cancel')" :visible.sync="cancelOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('inOutStock.inStockOrder.cancelCause')" prop="cancelCause">
          <el-input v-model="form.cancelCause" :placeholder="$t('inputTip') + $t('inOutStock.inStockOrder.cancelCause')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelSubmitForm">{{$t('sure')}}</el-button>
        <el-button @click="cancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mixins } from "@/mixin/pageSearchTable";
  import { listOrder, getOrder, delOrder, addOrder, updateOrder, orderCancel } from "@/api/inOutStock/inStockOrder";
  import { getToken } from "@/utils/auth";
  import detailPage from "./detail";

  export default {
    name: "Order",
    components: { detailPage },
    dicts: ['invoice_order_status','basic_area'],
    mixins:[mixins],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 选中行数据
        selectRow: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 入库单表格数据
        orderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        cancelOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          no: null,
          relOrderNo: null,
          orderStatus: null,
          workOrderNo: null,
          completeTime: null,
          totalActualQty: null,
          sort: null,
          orderType: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          cause: [
            { required: true, message: this.$t('inOutStock.inStockOrder.cause') + this.$t('notEmpty'), trigger: "blur" }
          ],
          cancelCause: [
            { required: true, message: this.$t('inOutStock.inStockOrder.cancelCause') + this.$t('notEmpty'), trigger: "blur" }
          ],
        },
        //传递给详情数据
        orderData:{},
        //页面下方明细的选项
        activeTab:'detailList',
        //页面初始化参数
        pageInit:{
          orderType: 1,
          names:[
            this.$t('inOutStock.inStockOrder.productionOrderManage'),
            this.$t('inOutStock.inStockOrder.storesReturnedOrderManage'),
            this.$t('inOutStock.inStockOrder.scrapOrderManage'),
            this.$t('inOutStock.inStockOrder.salesRefundOrderManage'),
            this.$t('inOutStock.inStockOrder.waitInspectionManage'),
            this.$t('inOutStock.inStockOrder.receivingOrderManage'),
            this.$t('inOutStock.inStockOrder.adjustOrderManage'),
            this.$t('inOutStock.inStockOrder.otherOrderManage')
          ]
        }
      };
    },
    created() {
      this.pageInit.orderType = this.$route.query.orderType;
      this.queryParams.orderType = this.$route.query.orderType;
      this.getList();
    },
    methods: {
      handleTabClick(value){
        console.log(value)
      },
      /** 查询入库单列表 */
      getList() {
        this.loading = true;
        this.rowSelection({});
        listOrder(this.queryParams).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //行选择
      rowSelection(row){
        this.orderData = row;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.cancelOpen = false;
        if(this.selectRow[0]){
          this.selectRow[0].cancelCause = null;
        }
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          no: null,
          orderType: this.pageInit.orderType,
          relOrderNo: null,
          orderStatus: 0,
          workOrderNo: null,
          completeTime: null,
          totalActualQty: null,
          sort: null,
          remark: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          cancelCause: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.queryParams.orderType = this.pageInit.orderType;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.selectRow = selection.map(item => item);
        this.single = selection.length!==1;
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = this.$t('add');
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getOrder(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = this.$t('edit');
        });
      },
      /** 取消按钮操作 */
      handleCancel() {
        this.reset();
        this.form = this.selectRow[0];
        this.cancelOpen = true;
      },
      /** 取消操作提交按钮 */
      cancelSubmitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            orderCancel({id: this.form.id, remark: this.form.cancelCause}).then(response => {
              this.$modal.msgSuccess(this.$t('operateSuc'));
              this.cancelOpen = false;
              this.getList();
            });
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateOrder(this.form).then(response => {
                this.$modal.msgSuccess(this.$t('editSuc'));
                this.open = false;
                this.getList();
              });
            } else {
              addOrder(this.form).then(response => {
                this.$modal.msgSuccess(this.$t('addSuc'));
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        const nos = row.no || this.nos;
        this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
          return delOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('deleteSuc'));
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const params = this.ids && this.ids.length > 0 ? {ids:this.ids} : {...this.queryParams};
        params.orderType = this.pageInit.orderType;
        params.pageSize = 0;
        const name = this.pageInit.names[this.pageInit.orderType - 1];
        this.download('inOutStock/inStockOrder/export', params, name + `_${new Date().getTime()}.xlsx`)
      },
    }
  };
</script>
